package com.bootdo.app.service.impl;

import com.bootdo.app.htmlVO.car.Car;
import com.bootdo.app.htmlVO.car.CarGoods;
import com.bootdo.app.htmlVO.car.CarInfo;
import com.bootdo.app.service.AppOrderService;
import com.bootdo.app.utils.AmountUtil;
import com.bootdo.app.utils.AppUtilXML;
import com.bootdo.app.utils.MyMath;
import com.bootdo.app.utils.ZimeBankUtil;
import com.bootdo.app.utils.redis.AppRedisUtil;
import com.bootdo.app.utils.returnresponse.ServerResponse;
import com.bootdo.appsystem.domain.*;
import com.bootdo.appsystem.service.*;
import com.bootdo.common.utils.HttpContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 【@author 】 @fan
 * 【@Email  】 mooncluyed@outlook.com
 * 【类解释  】
 * 【@Date   】 2018/5/18 0018
 **/
@Service
public class AppOrderServiceImpl implements AppOrderService {

    //订单主表
    @Autowired
    private OrderproductService orderproductService;
    //订单详情表
    @Autowired
    private OrderproductitemsService orderproductitemsService;
    //订单红包表
    @Autowired
    private OrderhongbaoService orderhongbaoService;
    //商家
    @Autowired
    private SellerService sellerService;
    @Autowired
    private ShouruService shouruService;
    @Autowired
    private RedrateService redrateService;
    @Autowired
    private UseraccountService useraccountService;
    @Autowired
    private UserdegreeService userdegreeService;
    @Autowired
    private RegectService regectService;
    @Autowired
    private OrderincomeService orderincomeService;
    @Autowired
    private RedsendService redsendService;
    @Autowired
    private OrderaddressinfoService orderaddressinfoService;
    @Autowired
    private MessageService messageService;



    //微信扫码创建一个订单
    @Override
    public ServerResponse creatOrderByWeChat(Integer sellerID, Double DdMoney, Integer orderParke) {

        SellerDO sellerDO = sellerService.get(sellerID);

        //创建一个新的订单
        OrderproductDO orderproductDO = new OrderproductDO();
        //订单性质，微信扫码订单
        orderproductDO.setPaytype(1);
        //订单总价
        orderproductDO.setTotalprice(DdMoney);
        //订单运费
        orderproductDO.setFreight(0.0);
        //订单数量
        orderproductDO.setBuycount(1);
        //订单性质
        orderproductDO.setOrderparke(orderParke);

        List<OrderproductitemsDO> orderproductitemsDOList = new ArrayList<>();
        OrderproductitemsDO orderproductitemsDO = new OrderproductitemsDO();
        //数量
        orderproductitemsDO.setBuycount(1);
        //商家id
        orderproductitemsDO.setSellerid(sellerID);
        //商品编号
        orderproductitemsDO.setPid(0);
        //价格
        orderproductitemsDO.setBuymoney(DdMoney);
        orderproductitemsDO.setGoodsstatus(0);
        orderproductitemsDOList.add(orderproductitemsDO);

        return this.creatOrder(orderproductDO, sellerDO, orderproductitemsDOList);
    }


    //    统一创建一个空的订单信息
    private ServerResponse creatOrder(OrderproductDO orderproductDO, SellerDO sellerDO, List<OrderproductitemsDO> orderproductitemsDOList) {

        /*第一步，将订单表存放到订单中，确定订单表中的数据;*/
        //获取session中的用户
        UseraccountDO useraccountDO = (UseraccountDO) HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);
        //随机产生一个订单号
        String ordercode = ZimeBankUtil.getOrderCode();
        //会员名称
        orderproductDO.setUid(useraccountDO.getUid());
        //订单创建时间
        orderproductDO.setOrdertime(new Date());
        //订单号
        orderproductDO.setOrdercode(ordercode);
        //订单状态为未付款状态
        orderproductDO.setOstatus(0);
        //商家名称
        orderproductDO.setSellername(sellerDO.getSellername());
        //商家id
        orderproductDO.setSellerid(sellerDO.getSellerid());
        //商家门头
        orderproductDO.setLeavemessage(sellerDO.getSellerimage());


        //将订单存放到订单表中,并获取订单编号
        Integer orderproductID = orderproductService.save(orderproductDO);

        /*第二步，将订单详情表存放在数据库中*/
        for (OrderproductitemsDO orderproductitemsDO : orderproductitemsDOList) {
            orderproductitemsDO.setOid(orderproductDO.getOid());
            //存储订单详情
            orderproductitemsService.save(orderproductitemsDO);
        }
        return ServerResponse.createBySuccess(orderproductID);
    }


    @Override
    public ServerResponse chackOrderStatu(String ordercode, Integer oId) {
//        获取订单信息
        List<OrderproductDO> orderproductList = orderproductService.getByOrderCode(ordercode);
        for (OrderproductDO orderproductDO: orderproductList) {
            //10 、 商城订单支付
            orderproductDO.setOrderparke(10);
            this.chackOrderStatus(orderproductDO);
        }
        return ServerResponse.createBySuccess("支付成功");
    }

    @Override
    public ServerResponse shengChengOrderStatu(Integer oId, Integer orderPark) {
        OrderproductDO orderproductDO = orderproductService.get(oId);
        orderproductDO.setOrderparke(orderPark);
        return this.chackOrderStatus(orderproductDO);
    }


    //订单支付成功
    private ServerResponse chackOrderStatus(OrderproductDO orderproductDO) {
        if (orderproductDO == null || orderproductDO.getOstatus() != 0) {
            return ServerResponse.createByErrorMessage("订单异常");
        }

//        获取配置
        HashMap<String, RedrateDO> redrateMap = AppRedisUtil.get("redrateMap");
        if(redrateMap == null){
            List<RedrateDO> redrateDOList = redrateService.list(new HashMap<>());
            redrateMap = new HashMap<>();
            for (RedrateDO redrateDO : redrateDOList) {
                redrateMap.put(redrateDO.getDescription(), redrateDO);
            }
            AppRedisUtil.put("redrateMap",redrateMap);
        }

        //创建一个订单收支
        Integer isOrderIncomeNull = 0;
        OrderincomeDO orderincomeDO = orderincomeService.getByCode(orderproductDO.getOrdercode());
        if(orderincomeDO == null){
            isOrderIncomeNull = 1;
            orderincomeDO = new OrderincomeDO().creatNewOrdercome();
        }
        orderincomeDO.setOrderprice(MyMath.add(orderincomeDO.getOrderprice(),orderproductDO.getTotalprice()));

//        1、查商家信息
        SellerDO sellerDO = sellerService.get(orderproductDO.getSellerid());
        //商家用户信息
        UseraccountDO sellerUserAccount = useraccountService.get(sellerDO.getUid());

//        2、查会员信息
        Integer userAccountId = orderproductDO.getUid();
        UseraccountDO useraccountDO = useraccountService.get(userAccountId);

//        9、商家本金
        Double benjin = this.benjinHongbao(sellerDO, orderproductDO);
        orderincomeDO.setSellerCorpus(MyMath.add(orderincomeDO.getSellerCorpus(),benjin));
//        3、商家上级奖励
        Double shangjia = this.sellerParentHongbao(orderproductDO, redrateMap, sellerUserAccount, sellerDO);
        orderincomeDO.setShangjiaTuiguang(MyMath.add(shangjia,orderincomeDO.getShangjiaTuiguang()));
//        4、会员上级奖励
        Double huiyuan = this.userParentHongbao(useraccountDO, orderproductDO, redrateMap, sellerDO);
        orderincomeDO.setYonghuTuiguang(MyMath.add(huiyuan,orderincomeDO.getYonghuTuiguang()));
//        5、股东奖励
        Double gudong = this.gudongHongbao(redrateMap, orderproductDO, sellerDO);
        orderincomeDO.setGudong(MyMath.add(gudong,orderincomeDO.getGudong()));
//        TODO 6、其他配置奖励


//        TODO 7、总监奖励
        orderincomeDO.setZongjian(MyMath.add(0.0,orderincomeDO.getZongjian()));

//        8、区域代理奖励
        Double daili = this.quyuDailiHongbao(sellerDO, orderproductDO, redrateMap);
        orderincomeDO.setDaili(daili);

        //存入订单收支情况
        orderincomeDO.setHongbao(0.0);
        orderincomeDO.setOrderCode(orderproductDO.getOrdercode());
        orderincomeDO.setOrdertime(orderproductDO.getOrdertime());

        if(isOrderIncomeNull == 1){
            orderincomeService.save(orderincomeDO);
        }else {
            orderincomeService.update(orderincomeDO);
        }

        //订单红包表存放
        OrderhongbaoDO orderhongbaoDO = new OrderhongbaoDO().creatOrderHongbaoDO(orderproductDO, sellerDO);
        orderhongbaoDO.setUserxishu(useraccountDO.getUserxishu());
        orderhongbaoService.save(orderhongbaoDO);

        //订单状态改变
        OrderproductDO oRet = new OrderproductDO();
        oRet.setOstatus(1);
        oRet.setOid(orderproductDO.getOid());
        oRet.setOrderparke(orderproductDO.getOrderparke());
        orderproductService.update(oRet);

        //改变商品详情列表
        orderproductitemsService.chickGoodsProductStatus(orderproductDO.getOid());

        //修改订单地址
        if(orderproductDO.getPaytype() == 10){
            this.chickAddressAndMssage(orderproductDO,sellerDO);
        }

        //TODO 发货提醒


        // 商家订单+1
        SellerDO linshiSeller = new SellerDO();
        linshiSeller.setSellerid(sellerDO.getSellerid());
        linshiSeller.setSelleroutnumber(sellerDO.getSelleroutnumber()+1);
        sellerService.update(linshiSeller);

        return ServerResponse.createBySuccess();
    }

    /**
     * 更改商品信息
     */
    void chickAddressAndMssage(OrderproductDO orderproductDO , SellerDO sellerDO){
//        修改地址状态
        OrderaddressinfoDO byOrderCode = orderaddressinfoService.getByOrderCode(orderproductDO.getOrdercode());
        if(byOrderCode != null){
            OrderaddressinfoDO orderaddressinfoDO = new OrderaddressinfoDO();
            orderaddressinfoDO.setId(byOrderCode.getId());
            orderaddressinfoDO.setStatus(1);
            orderaddressinfoService.update(orderaddressinfoDO);
        }

//        给商家发送系统消息
        messageService.faGoodsOrderSellerMessage(orderproductDO,sellerDO);

    }

    /**
     * 【@author】  @fan
     * 【方法解释】 用户上级的奖励
     * 【参数】
     *
     * @return void
     * 【@date】    2018/6/7 0007  下午 14:23
     */
    private Double userParentHongbao(UseraccountDO useraccountDO, OrderproductDO orderproductDO, HashMap<String, RedrateDO> redrateMap, SellerDO sellerDO) {
        //获取用户上级奖励配置
        //1、用户上级层级
        RedrateDO yhsjcj = redrateMap.get("yhsjcj");
        RedrateDO yhsjbl = redrateMap.get("yhsjbl");
        //计算奖励钱数          金额 * 设置比例 * （10 - 折扣） /  2        100*0.01*（10-8）/2
        Double money = AmountUtil.multiply(AmountUtil.multiply(yhsjbl.getRate(), orderproductDO.getTotalprice().doubleValue()), (10 - sellerDO.getSellercost()) / 2);
        Double countMoney = new Double(0.0);
//        商家的会员信息
        UseraccountDO userLinshi = new UseraccountDO();
        userLinshi = useraccountDO;
        //循环
        for (int i = 0; i < yhsjcj.getRate().intValue(); i++) {
            if (userLinshi.getParentid() == 0) {
                break;
            } else {
                //加钱！
                useraccountService.addMoney(userLinshi.getParentid(), money);
                //用户上级奖励增加
                countMoney += money;
                //存收入记录
                ShouruDO shouruDO = new ShouruDO().userPatentShouru(orderproductDO.getOrdercode(), money, i + 1, userLinshi.getParentid());
                shouruService.save(shouruDO);
                if (i != yhsjcj.getRate().intValue() - 1) {
                    userLinshi = useraccountService.get(userLinshi.getParentid());
                }
            }
        }
        return countMoney;
    }

    /**
     * 【@author】  @fan
     * 【方法解释】 商家上级的奖励
     * 【参数】
     *
     * @return void
     * 【@date】    2018/6/7 0007  下午 14:23
     * @Param [useraccountDO, orderproductDO, redrateMap]
     */
    private Double sellerParentHongbao(OrderproductDO orderproductDO, HashMap<String, RedrateDO> redrateMap, UseraccountDO sellerUserAccount, SellerDO sellerDO) {
        //获取商家上级奖励配置
        //1、商家上级层级
        RedrateDO sjsjcj = redrateMap.get("sjsjcj");
        RedrateDO sjsjbl = redrateMap.get("sjsjbl");
        //计算奖励钱数     金额 * 设置比例 * （10 - 折扣） /  2        100*0.01*（10-8）/2
        Double money = AmountUtil.multiply(AmountUtil.multiply(sjsjbl.getRate(), orderproductDO.getTotalprice().doubleValue()), (10 - sellerDO.getSellercost()) / 2);
        Double countMoney = new Double(0);
        UseraccountDO userLinshi = sellerUserAccount;
        if (AmountUtil.compareTo(money, 0.01) != -1) {
            //循环
            for (int i = 0; i < sjsjcj.getRate().intValue(); i++) {
                if (userLinshi.getParentid() == 0) {
                    break;
                } else {
                    //加钱！
                    useraccountService.addMoney(userLinshi.getParentid(), money);
                    //商家上级奖励增加
                    countMoney += money;

                    //存收入记录
                    ShouruDO shouruDO = new ShouruDO().sellerPatentShouru(orderproductDO.getOrdercode(), money, i + 1, userLinshi.getParentid());
                    shouruService.save(shouruDO);
                    //查询上级会员
                    if (i != sjsjcj.getRate().intValue() - 1) {
                        userLinshi = useraccountService.get(userLinshi.getParentid());
                    }
                }
            }
        }
        return countMoney;
    }

    /**
     * 【@author】  @fan
     * 【方法解释】 区域代理分红
     * 【参数】
     *
     * @return void
     * 【@date】    2018/6/7 0007  下午 22:50
     * @Param [sellerDO, orderproductDO, redrateMap]
     */
    private Double quyuDailiHongbao(SellerDO sellerDO, OrderproductDO orderproductDO, HashMap<String, RedrateDO> redrateMap) {

        //查看商家所在区域
        sellerDO.getRegectid();
        //从底向上发放区代红包

        RedrateDO qydlShengJi = redrateMap.get("qydlshengji");
        RedrateDO qydlShiJi = redrateMap.get("qydlshiji");
        RedrateDO qydlQuXian = redrateMap.get("qydlquxian");

        Double countMoney = new Double(0);

        //订单金额
        BigDecimal totalPrice = new BigDecimal(orderproductDO.getTotalprice());

        //区县层
        RegectDO qxRegectDO = regectService.get(sellerDO.getRegectid().doubleValue());

        //市级层
        RegectDO shijiRegectDO = new RegectDO();
        if (AmountUtil.compareTo(qxRegectDO.getParentId(), 0.0) != 0) {
            shijiRegectDO = regectService.get(qxRegectDO.getParentId());
        }

        //区县代理奖励
        if (AmountUtil.compareTo(qydlQuXian.getRate(), 0.0) == 1) {
            countMoney += this.dailiHongbao(qydlQuXian, orderproductDO, sellerDO, sellerDO.getRegectid());
        }
        //市级层奖励
        if (AmountUtil.compareTo(qydlShiJi.getRate(), 0.0) == 1) {
            if (AmountUtil.compareTo(qxRegectDO.getParentId(), 0.0) != 0) {
                countMoney += this.dailiHongbao(qydlShiJi, orderproductDO, sellerDO, qxRegectDO.getParentId().intValue());
            }
        }
        //省级层
        if (AmountUtil.compareTo(qydlShengJi.getRate(), 0.0) == 1) {
            if (AmountUtil.compareTo(shijiRegectDO.getParentId(), 0.0) != 0) {
                countMoney += this.dailiHongbao(qydlShengJi, orderproductDO, sellerDO, shijiRegectDO.getParentId().intValue());
            }
        }
        return countMoney;
    }


    //给代理发放红包
    private Double dailiHongbao(RedrateDO qydl, OrderproductDO orderproductDO, SellerDO sellerDO, Integer sellerRegectid) {
        //总发金额为       订单金额 * 设置比例 * （10 - 折扣） / 2
        BigDecimal qxMoney = new BigDecimal(AmountUtil.multiply(AmountUtil.multiply(qydl.getRate(), orderproductDO.getTotalprice().doubleValue()), (10 - sellerDO.getSellercost()) / 2));
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("regectid", sellerRegectid);
        List<UserdegreeDO> userdegreeDOS = userdegreeService.list(map);
        Double count = 0.0;
        //查询资质
        for (UserdegreeDO userdegreeDO : userdegreeDOS) {
            count += userdegreeDO.getDegreestatic();
        }
        Double countMoney = 0.0;

        //查得有资质
        if (AmountUtil.compareTo(count, 0.0) != 0) {
            //每一个资质应该获得的金额
            BigDecimal anyMoney = new BigDecimal(AmountUtil.divide(qxMoney.doubleValue(), count));
            for (UserdegreeDO userdegreeDO : userdegreeDOS) {
                //代理所应得的金额
                BigDecimal userMoney = new BigDecimal(AmountUtil.multiply(anyMoney.doubleValue(), userdegreeDO.getDegreestatic()));
                //判断是否有钱
                if (AmountUtil.compareTo(userMoney.doubleValue(), 0.01) != -1) {
                    //给代理用户加钱~
                    useraccountService.addMoney(userdegreeDO.getUid(), userMoney.doubleValue());
                    countMoney += userMoney.doubleValue();
                    //记录收入表
                    ShouruDO shouruDO = new ShouruDO().dailiShouru(userdegreeDO.getUid(), orderproductDO.getOrdercode(), userMoney.doubleValue());
                    shouruService.save(shouruDO);
                }
            }
        }
        return countMoney;
    }


    //股东发红包
    private Double gudongHongbao(HashMap<String, RedrateDO> redrateMap, OrderproductDO orderproductDO, SellerDO sellerDO) {
        RedrateDO gdfh = redrateMap.get("gdfh");
        //总发金额为       订单金额 * 设置比例 * （10 - 折扣） / 2
        BigDecimal gudongMoney = new BigDecimal(AmountUtil.multiply(AmountUtil.multiply(gdfh.getRate(), orderproductDO.getTotalprice().doubleValue()), (10 - sellerDO.getSellercost()) / 2));

        //给股东用户加钱~
        useraccountService.addMoney(gdfh.getRedrateshot().intValue(), gudongMoney.doubleValue());

        //记录收入表
        ShouruDO shouruDO = new ShouruDO().gudongShouru(gdfh.getRedrateshot().intValue(), orderproductDO.getOrdercode(), gudongMoney.doubleValue(), gdfh.getName());
        shouruService.save(shouruDO);

        return gudongMoney.doubleValue();
    }


    //商家本金红包
    private double benjinHongbao(SellerDO sellerDO, OrderproductDO orderproductDO) {
        //商家本金
        Double money = AmountUtil.multiply(orderproductDO.getTotalprice(), (sellerDO.getSellercost()) / 10);
        //给商家加钱
        useraccountService.addMoney(sellerDO.getUid(), money);
        //收入表
        ShouruDO shouruDO = new ShouruDO().benjinShouru(sellerDO.getUid(), orderproductDO.getOrdercode(), money);
        shouruService.save(shouruDO);
        return money;
    }


    public static void main(String[] args) {
        String kaishitime = "2018-01-01 00:00:00";
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.set(Calendar.DATE, now.get(Calendar.DATE) - 3);
        SimpleDateFormat sp = new SimpleDateFormat("YYYY-MM-dd");
        String jieshutime = sp.format(now.getTime()) + " 00:00:00";

        System.out.println(kaishitime);
        System.out.println(jieshutime);
    }


    @Override
    public ServerResponse fafangHongbao() {
//        获取配置
        List<RedrateDO> redrateDOList = redrateService.list(new HashMap<>());
        HashMap<String, RedrateDO> redrateMap = new HashMap<String, RedrateDO>();
        for (RedrateDO redrateDO : redrateDOList) {
            redrateMap.put(redrateDO.getDescription(), redrateDO);
        }

//        红包发放时间间隔
        RedrateDO hbffsjjg = redrateMap.get("hbffsjjg");

//        计算时间
        String kaishitime = "2018-01-01 00:00:00";
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.set(Calendar.DATE, now.get(Calendar.DATE) - hbffsjjg.getRate().intValue());
        SimpleDateFormat sp = new SimpleDateFormat("YYYY-MM-dd");
        String jieshutime = sp.format(now.getTime()) + " 00:00:00";

//      红包参数配置信息
        RedrateDO hbxs = redrateMap.get("hbxs");
        RedrateDO sjhbbl = redrateMap.get("sjhbbl");
        RedrateDO yhhbbl = redrateMap.get("yhhbbl");

        //  用户红包比例 = 红包系数 * 用户红包比例/（商家红包比例+用户红包比例）
        Double yonghuBiLi = MyMath.mul(hbxs.getRate(), MyMath.div(yhhbbl.getRate(), MyMath.add(sjhbbl.getRate(), yhhbbl.getRate()), 6));
        //  商家红包比例 = 红包系数 * 商家红包比例/（用户红包比例+商家红包比例）
        Double shangjiaBiLi = MyMath.mul(hbxs.getRate(), MyMath.div(sjhbbl.getRate(), MyMath.add(sjhbbl.getRate(), yhhbbl.getRate()), 6));

        Double shijiFafang = 0.0;
        Double hongbaoMoney = 0.0;

//        发放红包功能


//        1、查找所有红包订单信息
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("kaishitime", kaishitime);
        map.put("jieshutime", jieshutime);
        List<OrderhongbaoDO> orderhongbaoDOList = orderhongbaoService.list(map);

//        2、筛选红包订单
        for (OrderhongbaoDO orderhongbaoDO : orderhongbaoDOList) {

            OrderincomeDO orderincomeDO = orderincomeService.getByCode(orderhongbaoDO.getDdcode());

            //判断订单红包是否为正常数据
            if (orderhongbaoDO.getOrderstatus().equals(1)) {
                //用户系数
                Double userXiShu = orderhongbaoDO.getUserxishu();
                //商家系数
                Double sellerXiShu = orderhongbaoDO.getSellerxishu();
                //订单系数
                Double sellerOrderXiShu = orderhongbaoDO.getSellerorderxishu();

                //<!----******  一判断是否需要发放用户红包  *****---->
                if (AmountUtil.compareTo(orderhongbaoDO.getUsermoney(), orderhongbaoDO.getBackusermoney()) != -1) {
                    //3、计算用户红包订单的奖励金额
                    // 用户红包金额 = 用户奖励比例 * 订单金额 * （10 - 商家折扣） /  2 * 用户系数 * 订单系数
                    Double userMoney = MyMath.round(MyMath.mul(MyMath.mul(MyMath.mul(yonghuBiLi, MyMath.mul(orderhongbaoDO.getUsermoney(), MyMath.div(MyMath.sub(10.0, orderhongbaoDO.getSellercost()), 2.0, 6))), userXiShu), sellerOrderXiShu), 2);

                    //判断是否大于0.01
                    if (AmountUtil.compareTo(userMoney, 0.01) != -1) {
                        // 判断金额是否超出
                        //用户应发金额 + 红包已发金额 > 用户总金额   ,  已超出！！！
                        if (AmountUtil.compareTo(MyMath.add(userMoney, orderhongbaoDO.getBackusermoney()), orderhongbaoDO.getUsermoney()) != -1) {
                            //用户总金额 - 用户已发
                            userMoney = MyMath.round(MyMath.sub(orderhongbaoDO.getUsermoney(), orderhongbaoDO.getBackusermoney()), 2);
                            if (AmountUtil.compareTo(userMoney, 0.01) == -1) {
                                userMoney = 0.0;
                                orderhongbaoDO.setBackusermoney(orderhongbaoDO.getUsermoney());
                            }
                        }
                        //加钱
                        useraccountService.addMoney(orderhongbaoDO.getUid(), userMoney);
                        //实际发放记录增加
                        shijiFafang = MyMath.add(shijiFafang,userMoney);
                        //4、用户收入表增加数据
                        ShouruDO shouruDO = new ShouruDO().userHongBaoAdd(orderhongbaoDO, userMoney);
                        shouruDO.setUid(orderhongbaoDO.getUid());
                        shouruService.save(shouruDO);
                        // 订单支出加钱
                        orderhongbaoDO.setBackusermoney(MyMath.add(orderhongbaoDO.getBackusermoney(), userMoney));
                        hongbaoMoney = MyMath.add( hongbaoMoney , userMoney );
                    }
                }

                //<!----******  一判断是否需要发放用户红包  *****---->
                if (AmountUtil.compareTo(orderhongbaoDO.getSellermoney(), orderhongbaoDO.getBacksellermoney()) != -1) {
                    //5、计算商家红包订单的奖励金额
                    // 用户红包金额 = 商家奖励比例 * 商家红包 * 5 * 商家系数 * 订单系数
                    Double sellerMoney = MyMath.round(MyMath.mul(MyMath.mul(MyMath.mul(shangjiaBiLi, MyMath.mul(orderhongbaoDO.getSellermoney(), 5)), sellerXiShu), sellerOrderXiShu), 2);

                    //判断是否大于0.01
                    if (AmountUtil.compareTo(sellerMoney, 0.01) != -1) {
                        //判断金额是否超出
                        // 判断金额是否超出
                        //用户应发金额 + 商家已发金额 > 商家总金额   ,  已超出！！！
                        if (AmountUtil.compareTo(MyMath.add(sellerMoney, orderhongbaoDO.getBacksellermoney()), orderhongbaoDO.getSellermoney()) != -1) {
                            //商家总金额 - 商家已发金额
                            sellerMoney = MyMath.round(MyMath.sub(orderhongbaoDO.getSellermoney(), orderhongbaoDO.getBacksellermoney()), 2);
                            if (AmountUtil.compareTo(sellerMoney, 0.01) == -1) {
                                sellerMoney = 0.0;
                                orderhongbaoDO.setBacksellermoney(orderhongbaoDO.getSellermoney());
                            }
                        }
                        //加钱
                        useraccountService.addMoney(orderhongbaoDO.getSelleruserid(), sellerMoney);
                        //实际发放记录增加
                        shijiFafang = MyMath.add(shijiFafang,sellerMoney);
                        //4、用户收入表增加数据
                        ShouruDO shouruDO = new ShouruDO().sellerHongBaoAdd(orderhongbaoDO, sellerMoney);
                        shouruDO.setUid(orderhongbaoDO.getSelleruserid());
                        shouruService.save(shouruDO);

                        //  订单支出加钱
                        orderhongbaoDO.setBacksellermoney(MyMath.add(orderhongbaoDO.getBacksellermoney(), sellerMoney));
                        hongbaoMoney = MyMath.add( hongbaoMoney , sellerMoney );
                    }
                }

                //8、红包订单修改数据
                orderhongbaoService.update(orderhongbaoDO);
                //9、订单支出表修改数据
                if(orderincomeDO != null) {
                    orderincomeDO.setHongbao(MyMath.add(orderincomeDO.getHongbao(), hongbaoMoney));
                    orderincomeService.update(orderincomeDO);
                }

                //红包支出清零
                hongbaoMoney = 0.0;
            }
        }


//        10、发放完成，记录红包发放情况
        RedsendDO redsendDO = new RedsendDO();
        redsendDO.setBili(hbxs.getRate());
        //预算TODO
        redsendDO.setYusuan(0.0);
        redsendDO.setSendtime(new Date());
        redsendDO.setShiji(shijiFafang);
        redsendDO.setChae(MyMath.sub(shijiFafang,0.0));
        redsendDO.setRedstatus("测试发放");
        redsendService.save(redsendDO);


        return ServerResponse.createBySuccess("发放成功");
    }

    /**
     * 创建一个新的商品订单信息
     * @param car 购物信息
     * @param address 地址信息
     * @param totalMoney 总价
     * @return
     */
    @Override
    public ServerResponse creatNewGoodsOrder(Car car, ShipaddressDO address,Double totalMoney, Double totalFare) {

        UseraccountDO useraccount = (UseraccountDO) HttpContextUtils.getSessionObject(AppUtilXML.SESSION_CUSTOMER);
        //随机产生一个订单号
        String ordercode = ZimeBankUtil.getOrderCode();
        System.out.println("【car信息】" + car);

//        1、根据订单信息创建订单详情信息
        List<CarInfo> carInfoList = car.getCarInfo();
        for (CarInfo carinfo : carInfoList) {
            //1、创建一个新的订单信息
            OrderproductDO orderproduct = new OrderproductDO().creatNewGoodsOrderProductInfo(useraccount.getUid(),ordercode,carinfo);
            orderproductService.save(orderproduct);

            Double sellerMoney = 0.0;
            Double freight = 0.0;
            Integer totil = 0;
            List<CarGoods> goodList = carinfo.getGoodList();
            for (CarGoods carGoods:goodList) {
//                订单详情信息,根据订单存储
                OrderproductitemsDO orderproductitemsDO = new OrderproductitemsDO();
                orderproductitemsDO.setBuycount(carGoods.getNumber());
                orderproductitemsDO.setBuymoney(MyMath.mul(carGoods.getNumber(),carGoods.getPrice()));
                orderproductitemsDO.setGoodsstatus(0);
                orderproductitemsDO.setOid(orderproduct.getOid());
                orderproductitemsDO.setPid(carGoods.getPid());
                orderproductitemsDO.setSellerid(carinfo.getSellerId());
                orderproductitemsService.save(orderproductitemsDO);

//                商家金额 = 商家金额 + 商品数量 * 商品金额
                sellerMoney = MyMath.add(sellerMoney,MyMath.mul(carGoods.getNumber(),carGoods.getPrice()));
//                运费 = 商家金额 + 商品数量 * 运费
                freight = MyMath.add(freight,MyMath.mul(carGoods.getNumber(),carGoods.getVolume()));
//                商品数量
                totil = totil + carGoods.getNumber();
            }
            orderproduct.setTotalprice(MyMath.add(sellerMoney , freight));
            orderproduct.setFreight(freight);
            orderproduct.setBuycount(totil);
            orderproductService.update(orderproduct);
        }
//        3、根据商家创建订单收支信息
//        4、根据商家创建红包信息

//        保存地址信息
        System.out.println("【address信息】" + address);
        OrderaddressinfoDO orderaddressinfoDO = new OrderaddressinfoDO().creatNewAddressByShip(address);
        orderaddressinfoDO.setOrdercode(ordercode);
        orderaddressinfoService.save(orderaddressinfoDO);


        return ServerResponse.createBySuccess("创建订单成功");
    }


}
